# backend/orders/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ROLE_CHOICES = [
        ('dispatcher', '派单员'),
        ('worker', '接单员'),
    ]
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='worker')
    phone = models.CharField(max_length=15, blank=True)

    groups = models.ManyToManyField(
        'auth.Group',
        related_name='custom_user_set',  # 必须唯一
        blank=True,
        help_text='The groups this user belongs to.',
        verbose_name='groups',
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        related_name='custom_user_set',  # 必须唯一（可与上面相同）
        blank=True,
        help_text='Specific permissions for this user.',
        verbose_name='user permissions',
    )

    def __str__(self):
        return f"{self.username} ({self.get_role_display()})"


class Order(models.Model):
    STATUS_CHOICES = [
        ('pending', '待派单'),
        ('assigned', '已派单'),
        ('accepted', '已接单'),
        ('completed', '已完成'),
        ('closed', '已关闭'),
    ]

    title = models.CharField("订单标题", max_length=200)
    description = models.TextField("描述", blank=True)
    status = models.CharField("状态", max_length=20, choices=STATUS_CHOICES, default='pending')
    
    created_by = models.ForeignKey(
        'User',  # ← 引用自己的模型，用字符串即可
        on_delete=models.SET_NULL, 
        null=True, 
        related_name='created_orders',
        verbose_name="创建人"
    )
    assigned_to = models.ForeignKey(
        'User',
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        related_name='assigned_orders',
        verbose_name="指派给"
    )
    
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    def __str__(self):
        return f"{self.title} [{self.get_status_display()}]"

